package com.tekj.cxqcb.view.Module.activity.StoreModule;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.amap.api.services.core.PoiItem;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.entity.LocalMedia;
import com.tekj.cxqcb.R;
import com.tekj.cxqcb.config.enums.EventBusMsgBean;
import com.tekj.cxqcb.operation.BusinessDao;
import com.tekj.cxqcb.operation.resultBean.PubStatusBean;
import com.tekj.cxqcb.operation.resultBean.SelectByIdBean;
import com.tekj.cxqcb.operation.resultBean.UploadFiles;
import com.tekj.cxqcb.view.Module.activity.Address2Activity;
import com.tekj.cxqcb.view.Module.activity.PoiAroundSearchActivity;
import com.tekj.cxqcb.view.Module.adapter.Proposal2Adapter;
import com.tekj.cxqcb.view.Module.bean.ImageBean;
import com.tekj.cxqcb.view.Module.bean.UpShopInsertBean;
import com.tekj.cxqcb.view.Module.decoration.SpacesItemDecoration;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import common.base.activity.BaseActivity;
import common.base.operationHelper.Bean.BindingViewBean;
import common.tool.Tools;
import es.dmoral.toasty.Toasty;

import static com.tekj.cxqcb.config.enums.EventBusMsgBean.EnumStatus.店铺信息修改;

/**
 * 修改店铺资料
 */
public class ModifyShopActivity extends BaseActivity {

    @BindView(R.id.img_back)
    ImageView imgBack;
    @BindView(R.id.tv_l)
    TextView tvL;
    @BindView(R.id.ll_back)
    LinearLayout llBack;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.iv_r)
    ImageView ivR;
    @BindView(R.id.tv_r)
    TextView tvR;
    @BindView(R.id.ll_right)
    LinearLayout llRight;
    @BindView(R.id.rl_title_bg)
    RelativeLayout rlTitleBg;
    @BindView(R.id.et_name)
    EditText etName;
    @BindView(R.id.et_phone)
    EditText etPhone;
    @BindView(R.id.tv_adderss)
    TextView tvAdderss;
    @BindView(R.id.tv_detailed_adderss)
    EditText tvDetailedAdderss;
    @BindView(R.id.rv_photo)
    RecyclerView rvPhoto;
    @BindView(R.id.btn_Preservation)
    TextView btnPreservation;
    @BindView(R.id.tv_store_id)
    TextView tvStoreId;
    @BindView(R.id.tv_adderss2)
    TextView tvAdderss2;
    @BindView(R.id.img_photo1)
    ImageView imgPhoto1;

    private Proposal2Adapter adapter;
    private List<LocalMedia> localMedias;
    private SelectByIdBean.DataBeanX.DataBean data;
    private BusinessDao businessDao;
    private List<ImageBean> imgs;
    private String authorizationString;

    @Override
    public void init() {
        tvTitle.setText("修改店铺资料");
        data = (SelectByIdBean.DataBeanX.DataBean) getIntent().getSerializableExtra("data");
        businessDao = new BusinessDao(activity, this);
        setViewData(data);

    }

    @Override
    public int setLayout() {
        return R.layout.activity_modify_shop;
    }

    boolean isFirst;

    @Override
    public void initLoadStart() {
        if (isFirst) {
            loading.show();
            isFirst = false;
        } else
            showDialog();
    }

    @Override
    public void initLoadEnd() {
        loading.dismiss();
        dialog.dismiss();
    }

    @Override
    public void initBindingView(Object mBean) {

        BindingViewBean bindingViewBean = (BindingViewBean) mBean;
        switch (bindingViewBean.getmEnumStatus()) {
            case 多文件上传:
                UploadFiles uploadFiles = (UploadFiles) bindingViewBean.getBean();
                if (uploadFiles.getTypeName().equals("店铺头像")) {
                    authorizationString = uploadFiles.getData().getUploadFilePath();
                    return;
                }
                String[] files = uploadFiles.getData().getUploadFilePath().split(",");
                Iterator it = imgs.iterator();
                while (it.hasNext()) {
                    ImageBean m = (ImageBean) it.next();
                    if (!m.isInitial()) {
                        it.remove();
                    }
                }
                for (int i = 0; i < files.length; i++) {
                    imgs.add(new ImageBean(files[i], false));
                }
                break;
            case 添加申请店铺:
                PubStatusBean bean = (PubStatusBean) bindingViewBean.getBean();
                if (bean.getCode().equals("0000000")) {
                    finish();
                    EventBus.getDefault().post(new EventBusMsgBean(店铺信息修改, ""));
                } else {
                    Toasty.normal(activity, bean.getMsg()).show();
                }

                break;

        }

    }

    String regionid, region, province, city;
    PoiItem poiItem;
    double latitude, longitude;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK)
            switch (requestCode) {
                case 104:
                    if (resultCode != RESULT_OK) {
                        return;
                    }
                    province = data.getStringExtra("province");
                    city = data.getStringExtra("city");
                    region = data.getStringExtra("district");
                    regionid = data.getStringExtra("region");
                    tvAdderss.setText(province + " " + city + " " + region);
                    break;
                case 101:
                    List<LocalMedia> lists = PictureSelector.obtainMultipleResult(data);
                    List<File> list = new ArrayList<>();
                    for (int i = 0; i < lists.size(); i++) {
                        if (lists.get(i) != null && !lists.get(i).getCompressPath().equals("")) {
                            list.add(new File(lists.get(i).getCompressPath()));
                        }
                    }
                    businessDao.uploadFiles(list, "店铺形象");
                    addLocalMedias(lists);
                    adapter.setList(localMedias, localMedias.size() < 9 ? localMedias.size() + 1 : 9);
                    break;

                case 105:
                    poiItem = data.getParcelableExtra("poidata");
                    latitude = poiItem.getLatLonPoint().getLatitude();
                    longitude = poiItem.getLatLonPoint().getLongitude();
                    tvAdderss2.setText(poiItem.getSnippet());
                    break;
                case 106:
                    LocalMedia media = PictureSelector.obtainMultipleResult(data).get(0);
                    Tools.picasso(media.getCompressPath(), imgPhoto1);

                    List<File> list5 = new ArrayList<>();
                    list5.add(new File(media.getCompressPath() == null ? media.getPath() : media.getCompressPath()));
                    businessDao.uploadFiles(list5, "店铺头像");

                    break;
            }
    }


    @OnClick({R.id.ll_back, R.id.tv_adderss, R.id.tv_adderss2, R.id.btn_Preservation,R.id.img_photo1})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ll_back:
                finish();
                break;
            case R.id.tv_adderss:
                startActivityForResult(new Intent(activity, Address2Activity.class), 104);
                break;
            case R.id.tv_adderss2:
                startActivityForResult(new Intent(activity, PoiAroundSearchActivity.class), 105);
                break;
            case R.id.btn_Preservation:
                Tools.showNormalDialogOne(activity, "保存", "是否保存?", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        UpData();
                    }
                }, null);
                break;
            case R.id.img_photo1:
                Tools.InitPictureSelector(activity, false, 106, null, 1);
                break;
        }
    }

    /**
     * 设置界面中店铺信息
     */
    private void setViewData(SelectByIdBean.DataBeanX.DataBean bean) {
        region = bean.getRegion();
        province = bean.getProvince();
        city = bean.getCity();
        tvStoreId.setText("店铺ID：" + bean.getId());
        etName.setText(bean.getShopName());
        etPhone.setText(bean.getShopTel());
        tvAdderss.setText(bean.getProvinceName() + bean.getCityName() + bean.getRegionName());
        tvAdderss2.setText(bean.getAddress().split(",")[0]);
        authorizationString = bean.getAuthorization();
        Tools.picassoNetwork(bean.getAuthorization(), imgPhoto1);

        tvDetailedAdderss.setText(bean.getAddress().split(",").length == 2 ? bean.getAddress().split(",")[1] : "");
        longitude = bean.getLongitude();
        latitude = bean.getLatitude();
        regionid = bean.getRegion();


        imgs = new ArrayList<>();
        for (int i = 0; i < bean.getShopImage().length; i++) {
            imgs.add(new ImageBean(bean.getShopImage()[i], true));
        }
        localMedias = new ArrayList<>();
        for (int i = 0; i < data.getShopImage().length; i++) {
            LocalMedia media = new LocalMedia();
            media.setCompressed(true);
            media.setCompressPath(data.getShopImage()[i]);
            localMedias.add(media);
        }

        adapter = new Proposal2Adapter(activity, localMedias, localMedias.size() + 1);

        adapter.setOnCallbackListener(new Proposal2Adapter.OnCallbackListener() {
            @Override
            public void onAddPhotoClick() {
                //添加图片
                Tools.InitPictureSelector(activity, false, 101, getLocalMedias(), 9 - localMedias.size());
            }

            @Override
            public void onPicturePreview(int position) {
                //图片预览
//                PictureSelector.create(activity).externalPicturePreview(position, localMedias);
            }

            @Override
            public void onPictureDelete(int position) {
                localMedias.remove(position);
                imgs.remove(position);
                adapter.setList(localMedias, localMedias.size() + 1);
            }
        });

        rvPhoto.setLayoutManager(new GridLayoutManager(activity, 3));
        rvPhoto.setAdapter(adapter);
        rvPhoto.addItemDecoration(new SpacesItemDecoration(10));
    }

    /**
     * 获取除已上传图片（新增的本地图片）
     *
     * @return
     */
    List<LocalMedia> getLocalMedias() {
        List<LocalMedia> list = new ArrayList<>();
        for (int i = 0; i < localMedias.size(); i++) {
            if (!localMedias.get(i).getCompressPath().startsWith("http")) {
                list.add(localMedias.get(i));
            }
        }
        return list;
    }

    /**
     * 添加图片
     *
     * @param data
     */
    void addLocalMedias(List<LocalMedia> data) {
        boolean isadd;
        for (int i = 0; i < data.size(); i++) {
            isadd = true;
            for (int j = 0; j < localMedias.size(); j++) {
                if (localMedias.get(j).getCompressPath().equals(data.get(i).getCompressPath())) {
                    isadd = false;
                }
            }
            if (isadd)
                localMedias.add(data.get(i));
        }

    }

    /**
     * 店铺信息上传
     */
    void UpData() {

        UpShopInsertBean bean = new UpShopInsertBean();
        if (etName.getText().toString().equals("")) {
            Toasty.normal(activity, "请填写店铺名称").show();
            return;
        }
        bean.setShopName(etName.getText().toString());


        if (etPhone.getText().toString().equals("")) {
            Toasty.normal(activity, "请填写店铺电话").show();
            return;
        }
        bean.setShopTel(etPhone.getText().toString());

        if (regionid.equals("")) {
            Toasty.normal(activity, "请选择店铺所在省/市/区").show();
            return;
        }
//        bean.setProvince(province);
//        bean.setCity(city);
        bean.setRegion(regionid);

        if (tvAdderss2.getText().toString().equals("")) {
            Toasty.normal(activity, "请选择店铺详细地址").show();
            return;
        }
        bean.setAddress(tvAdderss2.getText().toString() + "," + tvDetailedAdderss.getText().toString());
        bean.setLatitude(latitude + "");
        bean.setLongitude(longitude + "");
        String imgString = "";
        for (int i = 0; i < imgs.size(); i++) {
            imgString = imgString + (i == 0 ? imgs.get(i).getName() : "," + imgs.get(i).getName());
        }
        bean.setShopImage(imgString);
        bean.setId(data.getId());

        bean.setAuthorization(authorizationString);

        businessDao.ApiShopUpdate(bean);

    }

}
